<?php

//对接文档 http://119.91.110.114/sakura/usmtaskadmin/file/tel.pdf
include_once "baseChannel.php";
// 时间相差8小时
date_default_timezone_set("Asia/Shanghai");
class wubai extends BaseChannel
{

    protected $appSecret;
    protected $appid;


    public function __construct($options)
    {
        parent::__construct($options);
        $this->appSecret = $options['appSecret'];
        $this->appid = $options['appid'];
    }
    // 计算签名提单需要签名  emptyWithSign 为空参与签名
    public function getSign($data, $emptyWithSign = false)
    {
        foreach ($data as $key => $val) {
            if (!$emptyWithSign) {
                if (empty($val)) {
                    unset($data[$key]);
                }
            }
            if (isset($data['sign'])) {
                unset($data['sign']);
            }
        }
        ksort($data);
        $data['secret'] = $this->appSecret;
        $str = http_build_query($data);
        $sign = md5($str);
        return strtoupper($sign);
    }
    public function queryBalance($params = [])
    {
        $data['appid'] = $this->appid;
        $data['sign'] = $this->getSign($data, true);
        $url = $this->query_balance_url;
        $return_str = $this->httpRequest($url, 'POST', $data);
        $return_data = json_decode($return_str, 1);
        if ($return_data['code'] == 0) {
            return [
                'error' => 0,
                'msg' =>  '查询成功',
                'balance' => $return_data['data']['balance'] ?? 0, //余额
                'credit' => 0, //授信 
                'code' => 200,
            ];
        }
        return [
            'error' => 1,
            'msg' => '查询失败',
            'code' => 500
        ];
    }
    //params :{push_order_sn:''} 
    public function queryOrder($params)
    {
        $data['appid'] = $this->appid;
        $data['out_order_no'] = $params['push_order_sn'];
        $data['sign'] = $this->getSign($data, true);

        $url = $this->query_order_url;
        $return_str = $this->httpRequest($url, 'POST', $data);
        $return_data = json_decode($return_str, 1);
        $ret = [
            'error' => 0,
            'order_status' => 2,
            'msg' => '初始化',
            'pz' => '', //凭证
            'post_data' => $data, //提交字符串
            'channel_data' => $return_str, //返回字符串
            'code' => 200
        ];
        //处理中
        if ($return_data['code'] == 0 && $return_data['data']['order_status'] == "RUNNING") {
            $ret['msg'] = '充值中';
        }
        // 成功
        if ($return_data['code'] == 0 && $return_data['data']['order_status'] == "FINISH") {
            $ret['order_status'] = self::OrderSuccess;
            $ret['msg'] = '查询充值完成:' . $return_data['message'];
        }
        // 失败
        if ($return_data['code'] == 0 && $return_data['data']['order_status'] == "FAILED") {
            $ret['order_status'] = self::OrderFail;
            $ret['msg'] = '查询充值失败:' . $return_data['message'];
        }
        return $ret;
    }
    public function submitOrder($mobile, $code, $params = [])
    {
        // 1:移动,2:联通,3:电信
        $data = [];
        $data['appid'] = $this->appid;

        $data['out_order_no'] = $params['push_order_sn'];
        $data['mobile'] = $mobile;
        $data['product_id'] = $code;

        $data['sign'] = $this->getSign($data, true);

        $return_str = $this->httpRequest($this->submit_order_url, 'POST', $data);
        $return_data = json_decode($return_str, 1);
        $ret = [
            'url' => $this->submit_order_url,
            'error' => -1,
            'msg' => '初始化',
            'channel_order' => $return_data['data']['order_no'] ?? '',
            'post_data' => json_encode($data),
            'channel_data' => $return_str,
            'code' => 200,
            'channel_order_price' =>  $return_data['data']['price'],
            'channel_balance' => $return_data['data']['balance'],
        ];
        if ($return_data['code'] == 0) {
            $ret['error'] = 0;
            $ret['msg'] = $return_data['message'] ?? '下单成功';
        } else {
            if (isset($return_data['code'])) {
                $ret['error'] = 1;
                $ret['code'] = 500;
                $ret['msg'] = $return_data['message'] ?? '下单失败';
            }
        }
        return $ret;
    }
    public function callback($params)
    {
        $this->callback_params = $params;
        //  $params['out_order_id']
        $this->channel_order_sn = $params['order_no'];
        $this->push_order_sn = $params['out_order_no'];
        //返回参数
        $res = $this->initCallBackParam();

        //订单状态
        $order_status = $params['order_status'];
        $msg = $params['error_msg'] ?? $params['order_status_text'];
        //凭证
        // $pz = $params['out_order_id'] ?? '';
        // $res['voucher'] = $pz;
        // 验证签名
        // $params['appid'] = $this->appid;
        $sign = $this->getSign($params, true);

        // if ($sign !== $params['sign']) {
        //     $res['error'] = 1;
        //     $res['msg'] = '签名不匹配';
        //     $res['resp_data'] = 'fail';
        //     $res['sign'] = $sign;
        //     return $res;
        // }
        if ($order_status == 'FINISH') {
            $res['order_status'] = self::OrderSuccess;
            $res['msg'] = $msg ?? '充值完成';
            $res['resp_data'] = 'success';
        }

        if ($order_status == "FAILED") {
            $res['order_status'] = self::OrderFail;
            $res['msg'] = $msg ?? '充值失败';
        }
        return $res;
    }
    //获取当前时间的毫秒
    public function msectime()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }
    // 获取当前时间包括毫秒
    public function getCurDate($isSecond = false)
    {
        if ($isSecond) {
            return time();
        } else {
            $time = $this->msectime();
            $timestamp = time() . substr($time, -3);
            return $timestamp;
        }
    }
}
